<template>
  <div class="batch-list-container">
    <el-container class="layout-container">
      <el-aside width="220px" class="sidebar">
        <div class="sidebar-content">
          <el-button @click="goBack" class="back-btn">
            <el-icon><ArrowLeft /></el-icon>
            返回主页
          </el-button>
        </div>
      </el-aside>

      <el-main class="main-content">
        <div class="page-header">
          <h1>屠宰企业 - 产品批号信息列表</h1>
          <p>浏览和管理产品批号信息</p>
        </div>

        <!-- 状态筛选按钮 -->
        <el-card class="filter-card" shadow="hover">
          <div class="status-filter">
            <el-button
              :type="activeStatus === 1 ? 'primary' : ''"
              @click="changeStatus(1)"
              class="status-btn"
            >
              <el-icon><DocumentAdd /></el-icon>
              新建 ({{ statusCounts[1] || 0 }})
            </el-button>
            <el-button
              :type="activeStatus === 2 ? 'primary' : ''"
              @click="changeStatus(2)"
              class="status-btn"
            >
              <el-icon><Clock /></el-icon>
              待确认 ({{ statusCounts[2] || 0 }})
            </el-button>
            <el-button
              :type="activeStatus === 3 ? 'primary' : ''"
              @click="changeStatus(3)"
              class="status-btn"
            >
              <el-icon><Check /></el-icon>
              已确认 ({{ statusCounts[3] || 0 }})
            </el-button>
            <el-button
              :type="activeStatus === 4 ? 'primary' : ''"
              @click="changeStatus(4)"
              class="status-btn"
            >
              <el-icon><Check /></el-icon>
              已下架 ({{ statusCounts[4] || 0 }})
            </el-button>
          </div>
        </el-card>

        <!-- 批号列表 -->
        <div class="batch-list">
          <div v-if="loading" class="loading-container">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <span>加载中...</span>
          </div>

          <div v-else-if="batchList.length === 0" class="empty-container">
            <el-empty description="暂无数据" />
          </div>

          <div v-else class="batch-cards">
            <el-card
              v-for="batch in batchList"
              :key="batch.batchId"
              class="batch-card"
              shadow="hover"
            >
              <template #header>
                <div class="card-header">
                  <span class="batch-id">批号: {{ batch.batchId }}</span>
                  <el-tag
                    :type="getStatusTagType(batch.state)"
                    class="status-tag"
                  >
                    {{ getStatusText(batch.state) }}
                  </el-tag>
                </div>
              </template>

              <div class="batch-info">
                <div class="info-item">
                  <span class="label">产品品种:</span>
                  <span class="value">{{ batch.type }}</span>
                </div>
                <div class="info-item">
                  <span class="label">合格证编号:</span>
                  <span class="value">{{ batch.quaId }}</span>
                </div>
                <div class="info-item">
                  <span class="label">检验日期:</span>
                  <span class="value">{{ formatDate(batch.batchDate) }}</span>
                </div>
                <div class="info-item" v-if="batch.testName">
                  <span class="label">检验员:</span>
                  <span class="value">{{ batch.testName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">屠宰企业编号:</span>
                  <span class="value">{{ batch.slauId }}</span>
                </div>
                <div class="info-item" v-if="batch.fbId">
                  <span class="label">养殖企业进场编号:</span>
                  <span class="value">{{ batch.fbId }}</span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="action-buttons">
                <!-- 新建状态：编辑和删除 -->
                <template v-if="batch.state === 1">
                  <el-button
                    type="primary"
                    size="small"
                    @click="editBatch(batch)"
                    class="action-btn"
                  >
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="deleteBatch(batch)"
                    class="action-btn"
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                  <el-button
                    type="success"
                    size="small"
                    @click="submitBatch(batch)"
                    class="action-btn"
                  >
                    <el-icon><Check /></el-icon>
                    提交
                  </el-button>
                </template>

                <!-- 待确认状态：详情 -->
                <template v-else-if="batch.state === 2">
                  <el-button
                    type="info"
                    size="small"
                    @click="viewDetails(batch)"
                    class="action-btn"
                  >
                    <el-icon><View /></el-icon>
                    详情
                  </el-button>
                </template>

                <!-- 已确认状态：下架 -->
                <template v-else-if="batch.state === 3">
                  <el-button
                    type="warning"
                    size="small"
                    @click="shelfBatch(batch)"
                    class="action-btn"
                  >
                    <el-icon><Remove /></el-icon>
                    下架
                  </el-button>
                </template>
              </div>
            </el-card>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 编辑批号弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑产品批号"
      width="700px"
      :before-close="handleEditDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editFormRef"
        label-width="200px"
        class="edit-form"
      >
        <!-- 1. 所属屠宰企业产品批号 -->
        <el-form-item label="所属屠宰企业产品批号：" prop="batchId">
          <el-input
            v-model="editForm.batchId"
            placeholder="请输入产品批号"
            class="form-input"
            disabled
          />
          <div class="form-tip">批号不可修改</div>
        </el-form-item>

        <!-- 2. 所属屠宰企业编号 -->
        <el-form-item label="所属屠宰企业编号：" prop="slauId">
          <el-input
            v-model="editForm.slauId"
            placeholder="请输入屠宰企业编号"
            class="form-input"
            @blur="checkEditSlauId"
            :class="{ 'error-border': editSlauIdExists }"
          />
          <div v-if="editSlauIdExists" class="error-text">
            <el-icon><Warning /></el-icon>
            该屠宰企业编号不存在
          </div>
        </el-form-item>

        <!-- 3. 所属养殖企业进场编号 -->
        <el-form-item label="所属养殖企业进场编号：" prop="fbId">
          <el-select
            v-model="editForm.fbId"
            filterable
            placeholder="请选择养殖企业进场编号"
            class="form-input"
            @focus="loadEditFarmBatchList"
            @change="handleEditFarmBatchChange"
            :disabled="editFarmBatchLoading"
          >
            <el-option
              v-for="batch in editFarmBatchList"
              :key="batch.batch_id"
              :label="batch.batch_id"
              :value="batch.batch_id"
            />
          </el-select>
          <div v-if="editFarmBatchLoading" class="loading-text">
            <el-icon><Loading /></el-icon>
            加载中...
          </div>
        </el-form-item>

        <!-- 4. 产品品种 -->
        <el-form-item label="产品品种：" prop="type">
          <el-input
            v-model="editForm.type"
            placeholder="根据进场编号自动显示"
            class="form-input"
            :disabled="true"
          />
          <div v-if="editProductTypeLoading" class="loading-text">
            <el-icon><Loading /></el-icon>
            加载中...
          </div>
        </el-form-item>

        <!-- 5. 肉类检验检疫合格证编号 -->
        <el-form-item label="肉类检验检疫合格证编号：" prop="quaId">
          <el-input
            v-model="editForm.quaId"
            placeholder="请输入合格证编号"
            class="form-input"
          />
        </el-form-item>

        <!-- 6. 官方检验员名称 -->
        <el-form-item label="官方检验员名称：" prop="testName">
          <el-input
            v-model="editForm.testName"
            placeholder="请输入检验员名称"
            class="form-input"
          />
        </el-form-item>

        <!-- 7. 批号检验日期 -->
        <el-form-item label="批号检验日期：" prop="batchDate">
          <el-date-picker
            v-model="editForm.batchDate"
            type="date"
            placeholder="选择检验日期"
            class="form-input"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditDialogClose" class="cancel-btn">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
          <el-button
            type="primary"
            @click="submitEditForm"
            :loading="editLoading"
            class="submit-btn"
          >
            <el-icon><Check /></el-icon>
            确定更新
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useTokenStore } from "@/stores/token.js";
import { useRouter } from "vue-router";
import {
  ArrowLeft,
  DocumentAdd,
  Clock,
  Check,
  Loading,
  Edit,
  Delete,
  View,
  Remove,
  Warning,
  Close,
} from "@element-plus/icons-vue";

export default {
  name: "BatchList",
  components: {
    ArrowLeft,
    DocumentAdd,
    Clock,
    Check,
    Loading,
    Edit,
    Delete,
    View,
    Remove,
    Warning,
    Close,
  },
  setup() {
    const router = useRouter();
    const tokenStore = useTokenStore();
    const activeStatus = ref(1);
    const batchList = ref([]);
    const statusCounts = ref({});
    const loading = ref(false);

    // 编辑相关状态
    const editDialogVisible = ref(false);
    const editFormRef = ref();
    const editLoading = ref(false);
    const editSlauIdExists = ref(false);
    const editFarmBatchList = ref([]);
    const editFarmBatchLoading = ref(false);
    const editProductTypeLoading = ref(false);
    const currentEditBatch = ref(null);

    // 编辑表单数据
    const editForm = reactive({
      batchId: "",
      slauId: "",
      fbId: "",
      type: "",
      quaId: "",
      testName: "",
      batchDate: "",
      originalState: 1,
    });

    // 状态映射
    const statusMap = {
      1: "新建",
      2: "待确认",
      3: "已确认",
      4: "已下架",
    };

    // 状态标签类型
    const statusTagType = {
      1: "primary",
      2: "warning",
      3: "success",
      4: "info",
    };

    // 编辑表单验证规则
    const editRules = {
      batchId: [{ required: true, message: "请输入产品批号", trigger: "blur" }],
      slauId: [
        { required: true, message: "请输入屠宰企业编号", trigger: "blur" },
      ],
      fbId: [
        {
          required: true,
          message: "请选择养殖企业进场编号",
          trigger: "change",
        },
      ],
      type: [{ required: true, message: "请选择产品品种", trigger: "change" }],
      quaId: [{ required: true, message: "请输入合格证编号", trigger: "blur" }],
      testName: [
        { required: true, message: "请输入检验员名称", trigger: "blur" },
      ],
      batchDate: [
        { required: true, message: "请选择检验日期", trigger: "change" },
      ],
    };

    // 获取状态文本
    const getStatusText = (state) => {
      return statusMap[state] || "未知状态";
    };

    // 获取状态标签类型
    const getStatusTagType = (state) => {
      return statusTagType[state] || "info";
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return "-";
      try {
        const date = new Date(dateString);
        // 加一天（仅用于显示）
        date.setDate(date.getDate());
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
      } catch (e) {
        console.error("日期格式化错误:", e);
        return dateString;
      }
    };

    // 返回主页
    const goBack = () => {
      router.push("/ent/slaghter");
    };

    // 切换状态
    const changeStatus = (status) => {
      activeStatus.value = status;
      loadBatchList();
    };

    // 获取 token
    const getToken = () => {
      return tokenStore.token;
    };

    // 带认证的请求函数
    const requestWithAuth = async (url, options = {}) => {
      const token = getToken();
      const headers = {
        "Content-Type": "application/json",
        ...options.headers,
      };

      if (token) {
        headers["Authorization"] = token;
      }

      const response = await fetch(url, {
        ...options,
        headers,
      });

      if (response.status === 401) {
        ElMessage.error("登录已过期，请重新登录");
        tokenStore.removeToken();
        window.location.href = "/login";
        throw new Error("认证失败");
      } else if (response.status === 403) {
        ElMessage.error("权限不足，无法访问该资源");
        throw new Error("权限不足");
      } else if (!response.ok) {
        throw new Error(`HTTP错误! 状态码: ${response.status}`);
      }

      return response;
    };

    // 加载批号列表
    const loadBatchList = async () => {
      loading.value = true;
      try {
        const response = await requestWithAuth(
          `http://localhost:8080/api/slauBatch/listByState?state=${activeStatus.value}`
        );

        const responseText = await response.text();

        if (!responseText.trim()) {
          throw new Error("服务器返回空响应");
        }

        let data;
        try {
          data = JSON.parse(responseText);
        } catch (parseError) {
          console.error("JSON解析错误:", parseError);
          throw new Error("服务器返回的数据格式不正确");
        }

        if (Array.isArray(data)) {
          batchList.value = data;
        } else if (data.data && Array.isArray(data.data)) {
          batchList.value = data.data;
        } else {
          batchList.value = [];
        }

        if (batchList.value.length === 0) {
          ElMessage.warning(
            `暂无${getStatusText(activeStatus.value)}状态的数据`
          );
        }
      } catch (error) {
        console.error("加载批号列表失败:", error);
        if (
          !error.message.includes("认证失败") &&
          !error.message.includes("权限不足")
        ) {
          if (error.message.includes("404")) {
            try {
              await loadAllBatchList();
            } catch (fallbackError) {
              ElMessage.error("加载批号列表失败");
              batchList.value = [];
            }
          } else {
            ElMessage.error("加载批号列表失败");
          }
        }
        batchList.value = [];
      } finally {
        loading.value = false;
      }
    };

    // 加载所有批号列表（备用方案）
    const loadAllBatchList = async () => {
      const response = await requestWithAuth(
        "http://localhost:8080/api/slauBatch/list"
      );

      const responseText = await response.text();

      if (!responseText.trim()) {
        throw new Error("服务器返回空响应");
      }

      let data;
      try {
        data = JSON.parse(responseText);
      } catch (parseError) {
        console.error("JSON解析错误:", parseError);
        throw new Error("服务器返回的数据格式不正确");
      }

      const allBatches = Array.isArray(data) ? data : data.data || [];
      batchList.value = allBatches.filter(
        (batch) => batch.state === activeStatus.value
      );

      if (batchList.value.length === 0) {
        ElMessage.warning(`暂无${getStatusText(activeStatus.value)}状态的数据`);
      }
    };

    // 加载状态统计
    const loadStatusCounts = async () => {
      try {
        const response = await requestWithAuth(
          "http://localhost:8080/api/slauBatch/statusCounts"
        );

        const responseText = await response.text();

        if (!responseText.trim()) {
          throw new Error("服务器返回空响应");
        }

        let data;
        try {
          data = JSON.parse(responseText);
        } catch (parseError) {
          console.error("JSON解析错误:", parseError);
          throw new Error("服务器返回的数据格式不正确");
        }

        statusCounts.value = data || {};
      } catch (error) {
        console.error("加载状态统计失败:", error);
        if (error.message.includes("404")) {
          statusCounts.value = { 1: 0, 2: 0, 3: 0, 4: 0 };
        }
      }
    };

    // 提交批号（新建状态 → 待确认状态）
    const submitBatch = async (batch) => {
      try {
        await ElMessageBox.confirm(
          `确定要提交产品批号 "${batch.batchId}" 给屠宰企业吗？`,
          "确认提交",
          {
            confirmButtonText: "确定提交",
            cancelButtonText: "取消",
            type: "warning",
            confirmButtonClass: "submit-confirm-btn",
          }
        );

        // 调用提交API
        const response = await requestWithAuth(
          `http://localhost:8080/api/slauBatch/submit/${batch.batchId}`,
          {
            method: "PUT",
          }
        );

        const result = await response.json();

        if (result.success) {
          ElMessage.success("提交成功");
          // 重新加载列表和状态统计
          loadBatchList();
          loadStatusCounts();
        } else {
          ElMessage.error(result.message || "提交失败");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("提交失败:", error);
          ElMessage.error("提交失败");
        }
      }
    };

    // 编辑批号
    const editBatch = async (batch) => {
      currentEditBatch.value = JSON.parse(JSON.stringify(batch));

      // 填充表单数据
      editForm.batchId = batch.batchId || "";
      editForm.slauId = batch.slauId ? batch.slauId.toString() : "";
      editForm.fbId = batch.fbId ? batch.fbId.toString() : "";
      editForm.type = batch.type || "";
      editForm.quaId = batch.quaId || "";
      editForm.testName = batch.testName || "";

      // 关键修改：确保日期格式正确
      editForm.batchDate = formatDateForForm(batch.batchDate);

      // 保存原始状态值
      editForm.originalState = batch.state || 1;

      // 重置状态
      editSlauIdExists.value = false;
      editFarmBatchList.value = [];
      editFarmBatchLoading.value = false;
      editProductTypeLoading.value = false;

      // 显示弹窗
      editDialogVisible.value = true;
    };

    // 专门用于表单的日期格式化函数
    const formatDateForForm = (dateString) => {
      if (!dateString) return "";
      try {
        // 直接使用原日期，不加一天
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
      } catch (e) {
        console.error("表单日期格式化错误:", e);
        return dateString;
      }
    };

    // 处理编辑弹窗关闭
    const handleEditDialogClose = () => {
      editDialogVisible.value = false;
      if (editFormRef.value) {
        editFormRef.value.resetFields();
      }
      currentEditBatch.value = null;
    };

    // 检查编辑表单的屠宰企业编号
    const checkEditSlauId = async () => {
      if (!editForm.slauId) return;

      try {
        const response = await requestWithAuth(
          `http://localhost:8080/api/slauBatch/checkSlauId?slauId=${editForm.slauId}`
        );
        const data = await response.json();
        editSlauIdExists.value = !data.exists;
      } catch (error) {
        console.error("检查屠宰企业编号失败:", error);
        if (
          !error.message.includes("认证失败") &&
          !error.message.includes("权限不足")
        ) {
          ElMessage.error("检查屠宰企业编号失败");
        }
      }
    };

    // 加载编辑表单的养殖企业进场编号列表
    const loadEditFarmBatchList = async () => {
      if (editFarmBatchList.value.length > 0) return;

      editFarmBatchLoading.value = true;
      try {
        const response = await requestWithAuth(
          "http://localhost:8080/api/farmBatch/batchList"
        );

        const responseText = await response.text();

        if (!responseText.trim()) {
          throw new Error("服务器返回空响应");
        }

        let data;
        try {
          data = JSON.parse(responseText);
        } catch (parseError) {
          console.error("JSON解析错误:", parseError);
          throw new Error("服务器返回的数据格式不正确");
        }

        if (Array.isArray(data)) {
          editFarmBatchList.value = data;
        } else {
          editFarmBatchList.value = [];
        }
      } catch (error) {
        console.error("加载养殖企业进场编号失败:", error);
        editFarmBatchList.value = [];
      } finally {
        editFarmBatchLoading.value = false;
      }
    };

    // 处理编辑表单进场编号选择变化
    const handleEditFarmBatchChange = async (batchId) => {
      editForm.type = "";

      if (batchId) {
        await loadEditProductTypeByBatchId(batchId);
      }
    };

    // 根据进场编号加载编辑表单的产品品种
    const loadEditProductTypeByBatchId = async (batchId) => {
      editProductTypeLoading.value = true;
      try {
        const response = await requestWithAuth(
          `http://localhost:8080/api/farmBatch/productTypeByBatchId?batchId=${batchId}`
        );

        if (response.ok) {
          const productType = await response.text();
          if (productType && productType.trim() !== '') {
            editForm.type = productType.trim();
          } else {
            ElMessage.warning("该进场编号暂无产品品种数据");
            editForm.type = "";
          }
        } else {
          throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }
      } catch (error) {
        console.error("加载产品品种失败:", error);
        ElMessage.error("加载产品品种失败");
        editForm.type = "";
      } finally {
        editProductTypeLoading.value = false;
      }
    };

    // 提交编辑表单
    const submitEditForm = async () => {
      console.log("开始提交编辑表单...");

      await nextTick();

      if (!editFormRef.value) {
        console.error("表单引用不存在");
        return;
      }

      try {
        console.log("开始表单验证...");
        const valid = await editFormRef.value.validate();
        console.log("表单验证结果:", valid);

        if (!valid) {
          ElMessage.error("请完善表单信息");
          return;
        }

        console.log("检查屠宰企业编号...", editSlauIdExists.value);
        if (editSlauIdExists.value) {
          ElMessage.error("屠宰企业编号不存在，请修改");
          return;
        }

        editLoading.value = true;
        console.log("开始准备更新数据...");

        let finalBatchDate = editForm.batchDate;

        // 如果日期选择器返回的是 Date 对象，转换为字符串格式
        if (editForm.batchDate instanceof Date) {
          const year = editForm.batchDate.getFullYear();
          const month = String(editForm.batchDate.getMonth() + 1).padStart(
            2,
            "0"
          );
          const day = String(editForm.batchDate.getDate()).padStart(2, "0");
          finalBatchDate = `${year}-${month}-${day}`;
        }

        console.log("保存的日期:", finalBatchDate);

        // 准备更新数据
        const updateData = {
          batchId: editForm.batchId,
          slauId: editForm.slauId,
          fbId: editForm.fbId,
          type: editForm.type,
          quaId: editForm.quaId,
          testName: editForm.testName,
          batchDate: finalBatchDate, // 直接使用，不做调整
          originalState: editForm.originalState || 1,
        };

        console.log("发送智能更新请求:", updateData);

        // 调用后端更新接口
        const response = await requestWithAuth(
          "http://localhost:8080/api/slauBatch/update",
          {
            method: "PUT",
            body: JSON.stringify(updateData),
          }
        );

        console.log("响应状态:", response.status);
        const result = await response.json();
        console.log("智能更新响应:", result);

        if (result.success) {
          if (result.changed) {
            ElMessage.success(result.message);
            handleEditDialogClose();
            loadBatchList();
            loadStatusCounts();
          } else {
            ElMessage.info(result.message);
            handleEditDialogClose();
          }
        } else {
          ElMessage.error(result.message || "更新失败");
        }
      } catch (error) {
        console.error("更新表单失败:", error);
        if (
          !error.message.includes("认证失败") &&
          !error.message.includes("权限不足")
        ) {
          ElMessage.error("更新表单失败: " + error.message);
        }
      } finally {
        editLoading.value = false;
      }
    };

    // 查看详情
    const viewDetails = (batch) => {
      ElMessageBox.alert(
        `
            <div style="text-align: left; line-height: 1.8;">
              <p><strong>产品批号:</strong> ${batch.batchId || "-"}</p>
              <p><strong>屠宰企业编号:</strong> ${batch.slauId || "-"}</p>
              <p><strong>养殖企业进场编号:</strong> ${batch.fbId || "-"}</p>
              <p><strong>产品品种:</strong> ${batch.type || "-"}</p>
              <p><strong>合格证编号:</strong> ${batch.quaId || "-"}</p>
              <p><strong>检验员:</strong> ${batch.testName || "-"}</p>
              <p><strong>检验日期:</strong> ${formatDate(batch.batchDate)}</p>
              <p><strong>状态:</strong> ${getStatusText(batch.state)}</p>
              <p><strong>备注:</strong> ${batch.remarks || "无"}</p>
            </div>
          `,
        "产品批号详情",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          customClass: "detail-dialog",
        }
      );
    };

    // 删除批号
    const deleteBatch = async (batch) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除产品批号 "${batch.batchId}" 吗？此操作不可恢复。`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        const response = await requestWithAuth(
          `http://localhost:8080/api/slauBatch/delete/${batch.batchId}`,
          {
            method: "DELETE",
          }
        );

        const result = await response.json();

        if (result.success) {
          ElMessage.success("删除成功");
          loadBatchList();
          loadStatusCounts();
        } else {
          ElMessage.error(result.message || "删除失败");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除失败:", error);
          ElMessage.error("删除失败");
        }
      }
    };

    // 下架批号
    const shelfBatch = async (batch) => {
      try {
        await ElMessageBox.confirm(
          `确定要下架产品批号 "${batch.batchId}" 吗？`,
          "确认下架",
          {
            confirmButtonText: "确定下架",
            cancelButtonText: "取消",
            type: "warning",
            confirmButtonClass: "shelf-confirm-btn",
          }
        );

        // 调用下架API
        const response = await requestWithAuth(
          `http://localhost:8080/api/slauBatch/shelf/${batch.batchId}`,
          {
            method: "PUT",
          }
        );

        const result = await response.json();

        if (result.success) {
          ElMessage.success("下架成功");
          // 重新加载列表和状态统计
          loadBatchList();
          loadStatusCounts();
        } else {
          ElMessage.error(result.message || "下架失败");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("下架失败:", error);
          ElMessage.error("下架失败");
        }
      }
    };

    // 初始化加载
    onMounted(() => {
      loadBatchList();
      loadStatusCounts();
    });

    return {
      activeStatus,
      batchList,
      statusCounts,
      loading,
      submitBatch,
      getStatusText,
      getStatusTagType,
      formatDate,
      goBack,
      changeStatus,
      editBatch,
      viewDetails,
      deleteBatch,
      shelfBatch,

      // 编辑相关
      editDialogVisible,
      editForm,
      editFormRef,
      editRules,
      editLoading,
      editSlauIdExists,
      editFarmBatchList,
      editFarmBatchLoading,
      editProductTypeLoading,
      handleEditDialogClose,
      submitEditForm,
      checkEditSlauId,
      loadEditFarmBatchList,
      handleEditFarmBatchChange,
      loadEditProductTypeByBatchId,
    };
  },
};
</script>

<style scoped>
.submit-confirm-btn {
  background-color: #67c23a;
  border-color: #67c23a;
}

.submit-confirm-btn:hover {
  background-color: #5daf34;
  border-color: #5daf34;
}

.shelf-confirm-btn {
  background-color: #e6a23c;
  border-color: #e6a23c;
}

.shelf-confirm-btn:hover {
  background-color: #cf9236;
  border-color: #cf9236;
}

.batch-list-container {
  height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.layout-container {
  height: 100%;
}

.sidebar {
  background: linear-gradient(180deg, #2d3748 0%, #1a202c 100%);
  padding: 20px;
  display: flex;
  align-items: flex-start;
}

.sidebar-content {
  width: 100%;
}

.back-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.back-btn .el-icon {
  margin-right: 8px;
}

.main-content {
  padding: 30px;
  background: transparent;
  overflow-y: auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #2d3748;
  font-size: 28px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #718096;
  font-size: 16px;
}

.filter-card {
  margin-bottom: 30px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
}

.status-filter {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.status-btn {
  border-radius: 8px;
  height: 40px;
  padding: 0 20px;
  transition: all 0.3s ease;
}

.status-btn:hover {
  transform: translateY(-2px);
}

.status-btn .el-icon {
  margin-right: 6px;
}

.batch-list {
  min-height: 400px;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #718096;
}

.loading-icon {
  font-size: 32px;
  margin-bottom: 16px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.batch-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.batch-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
  transition: all 0.3s ease;
}

.batch-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-id {
  font-weight: 600;
  color: #2d3748;
}

.status-tag {
  font-weight: 500;
}

.batch-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding: 4px 0;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #718096;
  font-size: 14px;
  font-weight: 500;
}

.value {
  color: #2d3748;
  font-size: 14px;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.action-btn {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
}

.action-btn .el-icon {
  margin-right: 4px;
}

/* 编辑表单样式 */
.edit-form {
  padding: 20px 0;
}

.form-tip {
  color: #718096;
  font-size: 12px;
  margin-top: 5px;
}

.error-border {
  border-color: #f56565;
}

.error-text {
  color: #f56565;
  font-size: 12px;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

.error-text .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.loading-text {
  color: #4299e1;
  font-size: 12px;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

.loading-text .el-icon {
  margin-right: 4px;
  font-size: 14px;
  animation: spin 1s linear infinite;
}

.form-input {
  width: 300px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.submit-btn,
.cancel-btn {
  border-radius: 6px;
  padding: 10px 20px;
}

.submit-btn {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
}

.submit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.cancel-btn:hover {
  transform: translateY(-1px);
}

.submit-btn .el-icon,
.cancel-btn .el-icon {
  margin-right: 6px;
}

@media (max-width: 768px) {
  .sidebar {
    width: 100% !important;
    height: auto;
  }

  .main-content {
    padding: 20px;
  }

  .page-header h1 {
    font-size: 24px;
  }

  .status-filter {
    flex-direction: column;
  }

  .status-btn {
    width: 100%;
  }

  .batch-cards {
    grid-template-columns: 1fr;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .form-input {
    width: 100%;
  }
}
</style>

<style>
.detail-dialog {
  min-width: 500px;
}
</style>